package com.nanbei.queue;

/**
 * @ClassDescription: 有序数组实现优先级队列
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/29 13:50
 */
public class OrderQueue<E extends Priority> implements QueueInterface<E>{

    Priority[] array;
    int size;

    public OrderQueue(int capacity) {
        this.array = new Priority[capacity];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }

        int i = size-1;
        while ( i>= 0 && array[i].getPriority() > value.getPriority()){
            array[i+1] = array[i];
            i--;
        }

        array[++i] = value;
        size++;

        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        E e = (E)array[--size];
        array[size] = null;
        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return (E)array[--size];
    }

    @Override
    public boolean isEmpty() {
        return size ==0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }
}
